<template>
  <div class="dealer-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">经销商管理</span>
        </div>
      </div>
      <h1 class="page-title">经销商管理</h1>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <router-link to="/dealer/add" class="v-button primary">
        <i class="iconfont icon-add"></i> 添加经销商
      </router-link>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索经销商名称/联系人"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-bar">
      <div class="filter-group">
        <label class="filter-label">所在地区</label>
        <BaseSelect
          v-model="filters.province.code"
          :options="provinceOptions"
          placeholder="请选择省"
          @change="(val) => {
            filters.province.name = provinceOptions.find(p => p.value === val)?.text || '';
            handleProvinceChange();
          }"
        />
        <BaseSelect
          v-model="filters.city.code"
          :options="cityOptions"
          placeholder="请选择市"
          @change="(val) => {
            filters.city.name = cityOptions.find(c => c.value === val)?.text || '';
            handleCityChange();
          }"
          :disabled="!filters.province.code"
        />
        <BaseSelect
          v-model="filters.district.code"
          :options="districtOptions"
          placeholder="请选择区县"
          @change="(val) => {
            filters.district.name = districtOptions.find(d => d.value === val)?.text || '';
          }"
          :disabled="!filters.city.code"
        />
      </div>

      <button class="v-button primary" @click="applyFilters">
        <i class="iconfont icon-filter-records"></i> 筛选
      </button>
      <button class="v-button outline" @click="resetFilters">
        <i class="iconfont icon-reset"></i> 重置
      </button>
    </div>

    <!-- 经销商表格 -->
    <div class="v-container">
      <table class="v-table">
        <thead>
          <tr>
            <th width="80">ID</th>
            <th>经销商名称</th>
            <th>联系人</th>
            <th>联系电话</th>
            <th>所在地区</th>
            <th>详细地址</th>
            <th width="180">创建时间</th>
            <th width="180">更新时间</th>
            <th width="170">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="dealer in dealerList" :key="dealer.id">
            <td>{{ dealer.id }}</td>
            <td>{{ dealer.name }}</td>
            <td>{{ dealer.contact_person || "-" }}</td>
            <td>{{ dealer.contact_phone || "-" }}</td>
            <td>{{ formatArea(dealer) }}</td>
            <td>{{ dealer.address || "-" }}</td>
            <td>{{ formatTimestamp(dealer.created_at) }}</td>
            <td>{{ formatTimestamp(dealer.updated_at) }}</td>
            <td>
              <div class="control">
                <router-link :to="'/dealer/edit/' + dealer.id" class="v-button">
                  <i class="iconfont icon-edit"></i> 编辑
                </router-link>
                <button class="v-button danger" @click="confirmDelete(dealer)">
                  <i class="iconfont icon-delete1"></i> 删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="!loading && dealerList.length === 0">
            <td colspan="9" class="empty-row">
              <i class="iconfont icon-empty"></i>
              {{ searchQuery ? "没有找到匹配的经销商" : "暂无数据" }}
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.totalPages > 1">
        <div class="v-pagination">
          <button
            class="v-button"
            :disabled="pagination.page === 1"
            @click="handlePageChange(pagination.page - 1)"
          >
            上一页
          </button>

          <template v-for="page in visiblePages" :key="page">
            <button
              class="v-button"
              :class="{ primary: page === pagination.page }"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
          </template>

          <button
            class="v-button"
            :disabled="pagination.page === pagination.totalPages"
            @click="handlePageChange(pagination.page + 1)"
          >
            下一页
          </button>
        </div>

        <div class="page-info">
          共 {{ pagination.total }} 条，当前 {{ pagination.page }}/{{
            pagination.totalPages
          }} 页
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import BaseSelect from "@/components/BaseSelect.vue";

const router = useRouter();

// 数据
const dealerList = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const areaMap = ref({}); // 存储地区码与名称的映射

// 分页信息
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  totalPages: 1,
});

// 地区数据
const provinceOptions = ref([]);
const cityOptions = ref([]);
const districtOptions = ref([]);

// 筛选条件
const filters = ref({
  province: { code: "", name: "" },
  city: { code: "", name: "" },
  district: { code: "", name: "" },
});

// 获取经销商列表
const fetchDealers = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数 - 使用省市区名称
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      keyword: searchQuery.value,
      province: filters.value.province.name,
      city: filters.value.city.name,
      district: filters.value.district.name
    };
    
    const res = await get("/dealer/list", params);
    if (res.code === 200) {
      dealerList.value = res.data.list || [];
      pagination.value = {
        page: res.data.pagination.page || 1,
        pageSize: res.data.pagination.pageSize || 10,
        total: res.data.pagination.total || 0,
        totalPages: res.data.pagination.totalPages || 1
      };
    } else {
      vToast.error(res.msg || "获取经销商列表失败");
    }
  } catch (error) {
    vToast.error("获取经销商列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 获取地区数据
const fetchAreas = async (type, parentCode = '') => {
  try {
    const params = { type };
    if (parentCode) params.code = parentCode;
    
    const res = await get("/city/list", params);
    
    if (res.code === 200) {
      return res.data.map(item => ({
        code: item.code,
        name: item.name,
        type: item.type
      }));
    }
    return [];
  } catch (error) {
    console.error("获取地区数据失败", error);
    return [];
  }
};

// 加载省份数据
const loadProvinces = async () => {
  const provinces = await fetchAreas('province');
  provinceOptions.value = provinces.map(p => ({
    value: p.code,
    text: p.name
  }));
};

// 省份变化时加载城市
const handleProvinceChange = async () => {
  filters.value.city = { code: "", name: "" };
  filters.value.district = { code: "", name: "" };
  if (filters.value.province.code) {
    const cities = await fetchAreas('city', filters.value.province.code);
    cityOptions.value = cities.map(c => ({
      value: c.code,
      text: c.name
    }));
  } else {
    cityOptions.value = [];
  }
  districtOptions.value = [];
};

// 城市变化时加载区县
const handleCityChange = async () => {
  filters.value.district = { code: "", name: "" };
  if (filters.value.city.code) {
    const districts = await fetchAreas('district', filters.value.city.code);
    districtOptions.value = districts.map(d => ({
      value: d.code,
      text: d.name
    }));
  } else {
    districtOptions.value = [];
  }
};

// 格式化地区显示
const formatArea = (dealer) => {
  const parts = [];
  if (dealer.province) parts.push(dealer.province);
  if (dealer.city && dealer.city !== dealer.province) parts.push(dealer.city);
  if (dealer.district) parts.push(dealer.district);
  return parts.join(' / ') || '-';
};

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 搜索
const handleSearch = () => {
  pagination.value.page = 1;
  fetchDealers();
};

const handleSearchClear = () => {
  searchQuery.value = "";
  pagination.value.page = 1;
  fetchDealers();
};

// 筛选
const applyFilters = () => {
  pagination.value.page = 1;
  fetchDealers();
};

const resetFilters = () => {
  filters.value = {
    province: { code: "", name: "" },
    city: { code: "", name: "" },
    district: { code: "", name: "" },
  };
  searchQuery.value = "";
  pagination.value.page = 1;
  fetchDealers();
};

// 分页
const handlePageChange = (page) => {
  if (page < 1 || page > pagination.value.totalPages) return;
  pagination.value.page = page;
  fetchDealers();
};

// 计算可见页码
const visiblePages = computed(() => {
  const { page, totalPages } = pagination.value;
  const pages = [];
  const maxVisible = 5;

  if (totalPages <= maxVisible) {
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i);
    }
  } else {
    const half = Math.floor(maxVisible / 2);
    let start = page - half;
    let end = page + half;

    if (start < 1) {
      start = 1;
      end = maxVisible;
    }

    if (end > totalPages) {
      end = totalPages;
      start = end - maxVisible + 1;
    }

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
  }

  return pages;
});

// 删除确认
const confirmDelete = (dealer) => {
  vConfirm({
    message: `确定要删除经销商【${dealer.name}】吗？`,
    onConfirm: () => deleteDealer(dealer.id),
  });
};

const deleteDealer = async (id) => {
  try {
    const res = await post("/dealer/delete", { id });

    if (res.code === 200) {
      vToast.success("经销商删除成功");
      fetchDealers();
    } else {
      vToast.error(res.msg || "删除失败");
    }
  } catch (error) {
    vToast.error("删除失败");
    console.error(error);
  }
};

// 初始化加载数据
onMounted(() => {
  loadProvinces();
  fetchDealers();
});

</script>

<style scoped lang="less">
.dealer-page {
  .breadcrumb {
    margin-bottom: 20px;
  }

  .action-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    .search-wrapper {
      flex: 1;
      max-width: 300px;
      margin-left: auto;

      .search-input {
        position: relative;
        display: flex;
        align-items: center;
        background: var(--v-card-bg);
        border-radius: var(--v-card-radius);
        border: 1px solid var(--v-border-color);
        padding: 0 10px;
        height: 36px;

        i {
          color: var(--v-text-light);
          margin-right: 8px;
        }

        input {
          flex: 1;
          border: none;
          background: transparent;
          outline: none;
          color: var(--v-text);

          &::placeholder {
            color: var(--v-text-light);
          }
        }

        .icon-close {
          cursor: pointer;
          margin-left: 8px;

          &:hover {
            color: var(--v-danger);
          }
        }
      }
    }
  }

  .filter-bar {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    .filter-group {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        font-size: 14px;
        color: var(--v-text-darker);
        white-space: nowrap;
      }

      .v-select {
        min-width: 120px;
      }
    }
  }

  .v-container {
    background-color: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    box-shadow: var(--v-shadow);
    padding: 20px;
    margin-top: 30px;
    transition: all 0.3s;
  }

  .v-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid var(--v-border-color);
    }

    th {
      font-weight: bold;
      color: #333;
    }

    tr:hover {
      background-color: #f9f9f9;
    }
  }

  .control {
    display: flex;
    align-items: center;
    gap: 8px;

    .v-button {
      padding: 0px 8px;
      font-size: 12px;
      min-width: auto;
      height: 32px;
      line-height: 32px;
      background: var(--v-background-pure);
      color: var(--v-sidebar-background);
      border: var(--v-sidebar-background) 1px solid;

      i {
        margin-right: 4px;
      }

      &.danger {
        color: var(--v-danger);
        border-color: var(--v-danger);
      }
    }
  }

  .empty-row {
    text-align: center;
    padding: 20px;
    color: var(--v-text-light);

    .iconfont {
      font-size: 48px;
      margin-bottom: 10px;
      display: block;
    }
  }

  /* 分页样式 */
  .pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--v-border-color);

    .v-pagination {
      display: flex;
      gap: 8px;

      .v-button {
        min-width: 36px;
        height: 36px;
        padding: 0 12px;

        &[disabled] {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }

    .page-info {
      color: var(--v-text-light);
      font-size: 14px;
    }
  }
}
</style>